<?php
/**
 * Created by PhpStorm.
 * User: sunjian
 * Date: 2018/3/10
 * Time: 8:56
 */

namespace backend\controllers;

use app\models\ExchangeCate;
use yii\web\Controller;
use Yii;
use yii\data\Pagination;

class ExchangeCateController  extends Controller
{
    public function actionList(){
        $query = ExchangeCate::find()->orderBy("create_time");
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count(), 'pageSize' => '20']);
        $cates = $query->offset($pages->offset)
            ->limit($pages->limit)->asArray()
            ->all();


        return $this->render("list",['cates'=>$cates,'p'=>$pages]);
    }

    public function actionAdd(){
        return $this->render("add");
    }

    public function actionAddCate(){
        $request = Yii::$app->request;
        if($request->isAjax){
            $cate = new ExchangeCate();
            $cate->title=$request->post("name");
            $cate->create_time=time();
            if($cate->save()){
                $return['status']=true;
            }else{
                $return['status']=false;
                $return['msg']=json_encode($cate->errors);
            }
            return json_encode($return);
        }
    }

    public function actionEdit(){
        $request = Yii::$app->request;
        $id = $request->get("id");

        $cate = ExchangeCate::findOne($id);
        return $this->render("edit",['cate'=>$cate]);
    }

    public function actionEditCate(){
        $request = Yii::$app->request;
        if($request->isAjax){
            $cate = ExchangeCate::findOne($request->post("id"));
            $cate->title= $request->post("name");

            if($cate->save()){
                $return['status']=true;
            }else{
                $return['status']=false;
                $return['msg']=json_encode($cate->errors);
            }
            return json_encode($return);
        }
    }

    public function actionDisable(){
        $request = Yii::$app->request;
        if($request->isAjax){
            $cate = ExchangeCate::findOne($request->post("id"));
            $cate->flag=0;
            if($cate->save()){
                $return['status']=true;
            }else{
                $return['status']=false;
                $return['msg']=json_encode($cate->errors);
            }
            return json_encode($return);
        }
    }
    public function actionEnable(){
        $request = Yii::$app->request;
        if($request->isAjax){
            $cate = ExchangeCate::findOne($request->post("id"));
            $cate->flag=1;
            if($cate->save()){
                $return['status']=true;
            }else{
                $return['status']=false;
                $return['msg']=json_encode($cate->errors);
            }
            return json_encode($return);
        }
    }
}